<template>
  <div class="rich-editor-container" :style="{ border: '1px solid #ccc' }">
    <Toolbar
        class="toolbar"
        :style="{ borderBottom: '1px solid #ccc' }"
        :editor="editorRef"
        :default-config="mergedToolbarConfig"
        :mode="props.mode"
    />
    <Editor
        class="editor-content"
        :style="{ height: typeof props.height === 'number' ? `${props.height}px` : props.height }"
        v-model="editorContent"
        :default-config="mergedEditorConfig"
        :mode="props.mode"
        @onCreated="handleCreated"
    />
    <!-- 文件管理 -->
    <el-dialog v-model="dialogVisible" title="上传图片" width="1200">
      <UploadFiles dialog :multiple="true" @useImage="handleUseImage" />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, shallowRef, watch, computed, onBeforeUnmount } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import UploadFiles from './UploadFiles.vue'
import '@wangeditor/editor/dist/css/style.css'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  height: {
    type: [Number, String],
    default: 500
  },
  mode: {
    type: String,
    default: 'default',
    // validator: value => ['default', 'simple'].includes(value)
  },
  toolbarConfig: {
    type: Object,
    default: () => ({})
  },
  editorConfig: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'change', 'created'])

// 编辑器实例 (必须使用 shallowRef)
const editorRef = shallowRef()
const editorContent = ref(props.modelValue)
const dialogVisible = ref(false)

const mergedEditorConfig = computed(() => {
  return {
    placeholder: '请输入内容...',
    // 自定义菜单项配置
    MENU_CONF: {},
    ...props.editorConfig
  }
})

// 合并工具栏配置
const mergedToolbarConfig = computed(() => {
  return {
    excludeKeys: [],
    ...props.toolbarConfig
  }
})

// 编辑器创建回调
const handleCreated = editor => {
  editorRef.value = editor
  emit('created', editor)
}

const handleUseImage = (url: string | string[]) => {
  const editor = editorRef.value
  if (editor) {
    editor.insertText(editor.getSelection(), {
      type: 'image',
      value: url,
      style: {}
    })
  }
}

// 内容变化监听
watch(editorContent, newVal => {
  emit('update:modelValue', newVal)
  emit('change', newVal)
})

// 外部内容同步
watch(() => props.modelValue, newVal => {
  if (newVal !== editorContent.value) {
    editorContent.value = newVal
  }
})

// 组件销毁时清理编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (!editor) return
  editor.destroy()
})
</script>

<style scoped>
.rich-editor-container {
  width: 100%;
  overflow: hidden;
}

.toolbar {
  border-bottom: 1px solid #ccc;
}

.editor-content {
  overflow-y: auto;
}
</style>